package com.fenyin.samples.study.xmemcached;

import java.io.IOException;
import java.util.concurrent.TimeoutException;

import net.rubyeye.xmemcached.MemcachedClient;
import net.rubyeye.xmemcached.MemcachedClientBuilder;
import net.rubyeye.xmemcached.XMemcachedClientBuilder;
import net.rubyeye.xmemcached.exception.MemcachedException;
import net.rubyeye.xmemcached.impl.KetamaMemcachedSessionLocator;
import net.rubyeye.xmemcached.utils.AddrUtil;

import org.junit.Test;

import com.google.code.yanf4j.config.Configuration;

/**
 * 使用Memcache的正常流程如下
 * 用户发起Memcache命令操作请求->将信息安装memcache的协议要求转换->使用通讯器与服务器进行交互传输
 * 
 */
public class MemcachedTest {

	@Test
	public void testSimpleClient(){
		MemcachedClientBuilder builder = new XMemcachedClientBuilder(AddrUtil.getAddresses("localhost:11211"));
		try {
			builder.setConnectionPoolSize(10);
			Configuration configuration = builder.getConfiguration();
			configuration.setReadThreadCount(3);
			configuration.setWriteThreadCount(4);
			configuration.setDispatchMessageThreadCount(5);
			MemcachedClient memcachedClient = builder.build();
			memcachedClient.set("hello", 0, "Hello,xmemcached");
			
			String value = memcachedClient.get("hello");
			System.out.println("hello=" + value);
			
			memcachedClient.delete("hello");
			
			value = memcachedClient.get("hello");
			System.out.println("hello=" + value);
			
			// close memcached client
			memcachedClient.shutdown();
		} catch (MemcachedException e) {
			System.err.println("MemcachedClient operation fail");
			e.printStackTrace();
		} catch (TimeoutException e) {
			System.err.println("MemcachedClient operation timeout");
			e.printStackTrace();
		} catch (InterruptedException e) {
			// ignore
		}catch (IOException e) {
			System.err.println("Shutdown MemcachedClient fail");
			e.printStackTrace();
		}
	}
	
	
	@Test
	public void testDistributeClient(){
		MemcachedClientBuilder builder = new XMemcachedClientBuilder(AddrUtil.getAddresses("localhost:11211"));
		try {
			//一致性Hash
			builder.setSessionLocator(new KetamaMemcachedSessionLocator());
			
			MemcachedClient memcachedClient = builder.build();
			memcachedClient.set("hello", 0, "Hello,xmemcached");
			
			String value = memcachedClient.get("hello");
			System.out.println("hello=" + value);
			
			memcachedClient.delete("hello");
			
			value = memcachedClient.get("hello");
			System.out.println("hello=" + value);
			
			// close memcached client
			memcachedClient.shutdown();
		} catch (MemcachedException e) {
			System.err.println("MemcachedClient operation fail");
			e.printStackTrace();
		} catch (TimeoutException e) {
			System.err.println("MemcachedClient operation timeout");
			e.printStackTrace();
		} catch (InterruptedException e) {
			// ignore
		}catch (IOException e) {
			System.err.println("Shutdown MemcachedClient fail");
			e.printStackTrace();
		}
	}

}
